package com.djzz.app.common_util.net;

import android.support.annotation.NonNull;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonRequest;
import com.djzz.app.common_util.utils.LogUtil;
import com.solidfire.gson.Gson;

import java.io.UnsupportedEncodingException;

/**
 * 自定义Volley请求类
 * Created by d on 2017/8/31.
 */

public class HttpRequest<T> extends JsonRequest<T> {

    private Class<T> responseClass;

    public HttpRequest(int method,
                       Class<T> responseClass,
                       String url,
                       Response.Listener<T> listener,
                       Response.ErrorListener errorListener) {
        super(method, url, null, listener, errorListener);
        this.responseClass = responseClass;
    }

    public HttpRequest(int method,
                       Class<T> responseClass,
                       String url,
                       String requestBody,
                       Response.Listener<T> listener,
                       Response.ErrorListener errorListener) {
        super(method, url, requestBody, listener, errorListener);
        this.responseClass = responseClass;
    }

    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(response.data, "UTF-8");
            T t = new Gson().fromJson(json, responseClass);
            LogUtil.i("hh",json);
            return Response.success(t, null);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return Response.error(new VolleyError(e));
        }
    }

    @Override
    public RetryPolicy getRetryPolicy() {
        RetryPolicy retryPolicy = new DefaultRetryPolicy(HttpManager.SOCKET_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        return retryPolicy;
    }

    @Override
    public Request<?> setRetryPolicy(RetryPolicy retryPolicy) {
        retryPolicy = new DefaultRetryPolicy(HttpManager.SOCKET_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        return super.setRetryPolicy(retryPolicy);
    }
}
